package com.mfy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfy.entity.Category;
import com.mfy.entity.User;
import com.mfy.entity.Video;
import com.mfy.dao.VideoMapper;
import com.mfy.feign.CategoryFeignClient;
import com.mfy.feign.UserFeignClient;
import com.mfy.service.IVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 视频 服务实现类
 * </p>
 *
 * @author mfy
 * @since 2023-05-09
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements IVideoService {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Override
    public IPage<Video> findAllByKeywords(String id, String name, String categoryId, String username, Page<Video> pageInfo) {
        //        1.判断用户传来的up主姓名是否为null
        Set<Integer> userIds = null;
        if(!StringUtils.isEmpty(username)){
            //        2.不为null远程调用
            List<User> users = userFeignClient.selectByName(username);
            //        3.获取到list集合里面的user的id信息。
            userIds = users.stream().map(user -> user.getId()).collect(Collectors.toSet());
        }
//        4.根据四个条件查询所有视频信息。Page对象。
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(id),"id",id)
                .like(!StringUtils.isEmpty(name),"title",name)
                .eq(!StringUtils.isEmpty(categoryId),"category_id",categoryId)
                .in(!ObjectUtils.isEmpty(userIds)&&!userIds.isEmpty(),"uid",userIds);
        IPage<Video> page = page((IPage<Video>) pageInfo, wrapper);
//        5.从page对象records遍历
        page.getRecords().stream().peek((video)->{
            Category category = categoryFeignClient.selectById(video.getCategoryId());
            video.setCategory(category.getName());
            User user = userFeignClient.selectById(video.getUid());
            video.setUploader(user);
        }).collect(Collectors.toList());
        return page;
    }
}
